package youwin.zk;

import java.io.FileReader;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import org.json.JSONObject;

import youwin.zk.bean.Tag;
import youwin.zk.bean.TagC;
import youwin.zk.myinterface.JavaScriptInterface;

/**
 * Hello world!
 *
 */
public class App {
	public static void main(String[] args) {
		/* 1.首先引入js引擎 */
		ScriptEngineManager manager = new ScriptEngineManager();
		//引擎名称传入JavaScript、js、javascript、nashorn、Nashorn 均可等价
		ScriptEngine engine = manager.getEngineByName("Nashorn");
		try {
			/* 2.然后读取js文件 */
			String path = Thread.currentThread().getContextClassLoader().getResource("").getPath(); // 获取targe路径
			// FileReader的参数为所要执行的js文件的路径
			engine.eval(new FileReader(path + "js/JavaScript1.js"));
			engine.eval(new FileReader(path + "js/JavaScript2.js"));
			if (engine instanceof Invocable) {
				Invocable invocable = (Invocable) engine;
				JavaScriptInterface executeMethod = invocable.getInterface(JavaScriptInterface.class);
				/* 3.最后反射执行js中脚本 */
				System.out.println(executeMethod.execute("str11", "str2"));
				Tag tag = new Tag();
				tag.setName("abc");
				tag.setValue("123.45");
				tag.setOther("hah j12.. 就是当年");
				System.out.println("executebean:" + executeMethod.executebean(tag));
				System.out.println("execute1:" + executeMethod.execute1());
				System.out.println("execute2:" + executeMethod.execute2());
				TagC TagC = new TagC();
				System.out.println("execute3:" + executeMethod.execute3(TagC));
				JSONObject jObject = new JSONObject();
				jObject.put("abc", "1212asl");
				System.out.println("execute4:" + executeMethod.execute4(jObject));
				System.out.println("execute5:" + executeMethod.execute5());
				System.out.println("execute6:" + executeMethod.execute6());
				executeMethod.execute7();
				executeMethod.execute8();
				executeMethod.execute9();
				executeMethod.execute10();
				System.out.println("end ---------------------- end");//验证js运行是和java同一个线程
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
